import { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Card, Table, Button, Input, Select, Space, Tag, message, Modal, Form, Upload } from 'antd'
import { PlusOutlined, DownloadOutlined, SearchOutlined, ReloadOutlined, UploadOutlined } from '@ant-design/icons'
import { 
  fetchBookList, 
  addBook, 
  editBook, 
  removeBook, 
  removeBatchBooks,
  resetCurrentBook 
} from '@/store/slices/bookSlice'
import { fetchCategoryTree } from '@/store/slices/categorySlice'
import './index.scss'

const BookManagement = () => {
  const dispatch = useDispatch()
  const { bookList, total, currentPage, pageSize, loading } = useSelector((state) => state.book)
  const { categoryTree } = useSelector((state) => state.category)
  
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [modalType, setModalType] = useState('add') // 'add' or 'edit'
  const [currentRecord, setCurrentRecord] = useState(null)
  const [form] = Form.useForm()
  
  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    title: '',
    author: '',
    categoryId: null,
    publisher: ''
  })

  // 初始化加载数据
  useEffect(() => {
    loadBookList()
    dispatch(fetchCategoryTree())
  }, [])

  // 加载图书列表
  const loadBookList = (params = {}) => {
    dispatch(fetchBookList({
      page: params.page || currentPage,
      size: params.size || pageSize,
      ...searchForm,
      ...params
    }))
  }

  // 搜索
  const handleSearch = () => {
    loadBookList({ page: 1 })
  }

  // 重置
  const handleReset = () => {
    setSearchForm({
      title: '',
      author: '',
      categoryId: null,
      publisher: ''
    })
    dispatch(fetchBookList({ page: 1, size: pageSize }))
  }

  // 打开新增对话框
  const handleCreate = () => {
    setModalType('add')
    setCurrentRecord(null)
    form.resetFields()
    setIsModalVisible(true)
  }

  // 打开编辑对话框
  const handleEdit = (record) => {
    setModalType('edit')
    setCurrentRecord(record)
    form.setFieldsValue({
      title: record.title,
      author: record.author,
      publisher: record.publisher,
      categoryId: record.categoryId,
      description: record.description,
      cover: record.cover,
      url: record.url
    })
    setIsModalVisible(true)
  }

  // 删除
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这本图书吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const result = await dispatch(removeBook(id))
        if (result.type.includes('fulfilled')) {
          message.success('删除成功')
          loadBookList()
        } else {
          message.error('删除失败')
        }
      }
    })
  }

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的图书')
      return
    }
    
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 本图书吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const result = await dispatch(removeBatchBooks(selectedRowKeys))
        if (result.type.includes('fulfilled')) {
          message.success('批量删除成功')
          setSelectedRowKeys([])
          loadBookList()
        } else {
          message.error('批量删除失败')
        }
      }
    })
  }

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      
      if (modalType === 'add') {
        const result = await dispatch(addBook(values))
        if (result.type.includes('fulfilled')) {
          message.success('新增成功')
          setIsModalVisible(false)
          loadBookList()
        } else {
          message.error(result.payload || '新增失败')
        }
      } else {
        const result = await dispatch(editBook({ 
          id: currentRecord.id, 
          data: values 
        }))
        if (result.type.includes('fulfilled')) {
          message.success('更新成功')
          setIsModalVisible(false)
          loadBookList()
        } else {
          message.error(result.payload || '更新失败')
        }
      }
    } catch (error) {
      // 表单验证失败，Ant Design会自动显示错误提示
    }
  }

  // 关闭对话框
  const handleCloseModal = () => {
    setIsModalVisible(false)
    form.resetFields()
    dispatch(resetCurrentBook())
  }

  // 分页改变
  const handlePageChange = (page, size) => {
    loadBookList({ page, size })
  }

  // 表格列配置
  const columns = [
    {
      title: '图书ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center'
    },
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      width: 80,
      render: (cover) => cover ? (
        <img src={cover} alt="封面" style={{ width: 50, height: 70, objectFit: 'cover' }} />
      ) : (
        <div style={{ width: 50, height: 70, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          无
        </div>
      )
    },
    {
      title: '图书名称',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 120
    },
    {
      title: '出版社',
      dataIndex: 'publisher',
      key: 'publisher',
      width: 150,
      ellipsis: true
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
      render: (categoryName) => {
        return categoryName ? <Tag color="blue">{categoryName}</Tag> : <Tag color="default">未分类</Tag>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time) => time ? new Date(time).toLocaleString('zh-CN') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" size="small" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      )
    }
  ]

  // 行选择
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys)
    }
  }

  // 构建分类树选项
  const buildCategoryOptions = (tree) => {
    if (!tree || tree.length === 0) return []
    
    return tree.map(node => ({
      label: node.name,
      value: node.id,
      children: node.children && node.children.length > 0 ? buildCategoryOptions(node.children) : undefined
    }))
  }

  return (
    <div className="book-management-container">
      {/* 搜索表单 */}
      <Card className="search-card" title="查询表格">
        <div className="search-form">
          <div className="form-row">
            <div className="form-item">
              <label>图书名称</label>
              <Input
                placeholder="请输入图书名称"
                value={searchForm.title}
                onChange={(e) => setSearchForm({ ...searchForm, title: e.target.value })}
                onPressEnter={handleSearch}
              />
            </div>
            <div className="form-item">
              <label>作者</label>
              <Input
                placeholder="请输入作者名称"
                value={searchForm.author}
                onChange={(e) => setSearchForm({ ...searchForm, author: e.target.value })}
                onPressEnter={handleSearch}
              />
            </div>
            <div className="form-item">
              <label>出版社</label>
              <Input
                placeholder="请输入出版社"
                value={searchForm.publisher}
                onChange={(e) => setSearchForm({ ...searchForm, publisher: e.target.value })}
                onPressEnter={handleSearch}
              />
            </div>
            <div className="form-item">
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                查询
              </Button>
            </div>
          </div>

          <div className="form-row">
            <div className="form-item">
              <label>图书分类</label>
              <Select
                placeholder="请选择分类"
                value={searchForm.categoryId}
                onChange={(value) => setSearchForm({ ...searchForm, categoryId: value })}
                style={{ width: '100%' }}
                allowClear
              >
                {categoryTree.map(cat => (
                  <Select.Option key={cat.id} value={cat.id}>{cat.name}</Select.Option>
                ))}
              </Select>
            </div>
            <div className="form-item">
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </div>
          </div>
        </div>
      </Card>

      {/* 操作按钮和表格 */}
      <Card className="table-card">
        <div className="table-toolbar">
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              新增图书
            </Button>
            {selectedRowKeys.length > 0 && (
              <Button danger onClick={handleBatchDelete}>
                批量删除 ({selectedRowKeys.length})
              </Button>
            )}
          </Space>
          <Button icon={<DownloadOutlined />}>
            导出数据
          </Button>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={bookList}
          loading={loading}
          rowKey="id"
          pagination={{
            total,
            current: currentPage,
            pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: handlePageChange
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新增/编辑对话框 */}
      <Modal
        title={modalType === 'add' ? '新增图书' : '编辑图书'}
        open={isModalVisible}
        onOk={handleSubmit}
        onCancel={handleCloseModal}
        width={800}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            title: '',
            author: '',
            publisher: '',
            categoryId: null,
            description: '',
            cover: '',
            url: ''
          }}
        >
          <Form.Item
            label="图书名称"
            name="title"
            rules={[{ required: true, message: '请输入图书名称' }]}
          >
            <Input placeholder="请输入图书名称" />
          </Form.Item>

          <Form.Item
            label="作者"
            name="author"
            rules={[{ required: true, message: '请输入作者' }]}
          >
            <Input placeholder="请输入作者" />
          </Form.Item>

          <Form.Item
            label="出版社"
            name="publisher"
          >
            <Input placeholder="请输入出版社" />
          </Form.Item>

          <Form.Item
            label="分类"
            name="categoryId"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="请选择分类">
              {categoryTree.map(cat => (
                <Select.Option key={cat.id} value={cat.id}>{cat.name}</Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="封面URL"
            name="cover"
          >
            <Input placeholder="请输入封面图片URL" />
          </Form.Item>

          <Form.Item
            label="详情URL"
            name="url"
          >
            <Input placeholder="请输入图书详情URL" />
          </Form.Item>

          <Form.Item
            label="图书简介"
            name="description"
          >
            <Input.TextArea rows={4} placeholder="请输入图书简介" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default BookManagement
